﻿#region

using System;
using System.Linq;
using System.Web.Mvc;
using Class.Web.Mvc;
using Telerik.Web.Mvc;
using ThuySan.Bussiness;
using ThuySan.Models;

#endregion

namespace ThuySan.Areas.Backend.Controllers
{
    [Authorize]
    public class SettingController : BaseController
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        public ActionResult Index()
        {
            return View();
        }

        [GridAction]
        public ActionResult GetList()
        {
            return View(new GridModel(_unitOfWork.SettingRepository.Select().Select(c => new
            {
                c.SettingId,
                c.Name,
                c.Description
            })));
        }

        public ActionResult Edit(string id)
        {
            int guid;
            if (int.TryParse(id, out guid))
            {
                Setting setting = _unitOfWork.SettingRepository.SelectbyId(guid);
                if (setting != null)
                {
                    SettingModel settingModel = setting;
                    return View(settingModel);
                }
            }
            return RedirectToAction("Index");
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(SettingModel settingModel)
        {
            if (ModelState.IsValid)
            {
                Setting setting = _unitOfWork.SettingRepository.SelectbyId(settingModel.SettingId);
                settingModel.Update(setting);
                if (_unitOfWork.SettingRepository.CheckUpdateSetting(setting))
                {
                    Exception exception;
                    _unitOfWork.SettingRepository.Update(setting, out exception);
                    if (setting.IsUpload ?? false)
                    {
                        setting.Value = SaveResource("thumbnail", "Setting", setting.Value, setting);
                        _unitOfWork.AcceptChanges();
                    }
                    else
                    {
                        setting.Value = settingModel.Value;
                        _unitOfWork.AcceptChanges();
                    }
                    return RedirectToAction("Index");
                }
            }
            return View(settingModel);
        }

    }
}
